package com.cmas.platform.service.impl;

import java.util.List;

import com.aidex.common.constant.Constants;
import com.aidex.common.core.domain.model.LoginUser;
import com.aidex.common.core.redis.RedisLock;
import com.aidex.common.utils.SecurityUtils;
import com.alibaba.fastjson2.JSONObject;
import com.cmas.platform.cache.ReLoadRedis;
import com.cmas.platform.domain.Comment;
import com.cmas.platform.domain.Post;
import com.cmas.platform.domain.em.UserLikeTypeEnum;
import com.cmas.platform.mapper.CommentMapper;
import com.cmas.platform.mapper.PostMapper;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.aidex.common.core.domain.BaseEntity;
import com.aidex.common.utils.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cmas.platform.mapper.UserLikeMapper;
import com.cmas.platform.domain.UserLike;
import com.cmas.platform.service.UserLikeService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户点赞表Service业务层处理
 *
 * @author su
 * @email 1218819874@qq.com
 * @date 2023-05-03
 */
@Service
public class UserLikeServiceImpl extends ServiceImpl<UserLikeMapper, UserLike> implements UserLikeService {

    private static final Logger log = LoggerFactory.getLogger(UserLikeServiceImpl.class);

    @Autowired
    private PostMapper postMapper;

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private RedisLock redisLock;


    @Autowired
    private ReLoadRedis reLoadRedis;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * 查询用户点赞表列表
     *
     * @param userLike 用户点赞表
     * @return 用户点赞表
     */
    @Override
    public List<UserLike> selectUserLikeList(UserLike userLike) {
        QueryWrapper<UserLike> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(userLike.getUserId())) {
            queryWrapper.lambda().eq(UserLike::getUserId, userLike.getUserId());
        }
        if (StringUtils.isNotEmpty(userLike.getItemId())) {
            queryWrapper.lambda().eq(UserLike::getItemId, userLike.getItemId());
        }
        List<UserLike> userLikeList = baseMapper.selectList(queryWrapper);
        return userLikeList;
    }

    /**
     * 批量删除用户点赞表
     *
     * @param ids 需要删除的用户点赞表ID
     * @return 结果
     */
    @Transactional(readOnly = false)
    @Override
    public int deleteUserLikeByIds(String[] ids) {
        return baseMapper.deleteUserLikeByIds(ids, BaseEntity.DEL_FLAG_DELETE);
    }

    @Override
    public boolean userLike(UserLike userLike, String type) {
        if (StringUtils.isNotEmpty(userLike.getItemId())) {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            UserLike oldLike = baseMapper.selectOne(new QueryWrapper<UserLike>().lambda()
                    .eq(UserLike::getUserId, loginUser.getUserId())
                    .eq(UserLike::getItemId, userLike.getItemId()));
            if (oldLike != null) {
                BeanUtils.copyProperties(oldLike, userLike);
            }
            userLike.setUserId(loginUser.getUserId());
            if (type.equals(UserLikeTypeEnum.POST.getValue())) {
                userLikePost(userLike);
                return true;
            } else if (type.equals(UserLikeTypeEnum.COMMENT.getValue())) {
                userLikeComment(userLike);
                return true;
            }
        }
        return false;
    }

    /**
     * 点赞评论
     *
     * @param userLike
     */
    private void userLikeComment(UserLike userLike) {
        //加锁
        String lockKey = "commentLockKey";
        redisLock.lock(lockKey);
        Comment comment = commentMapper.selectById(userLike.getItemId());
        userLike.setItemId(comment.getId());
        userLike.setType(UserLikeTypeEnum.COMMENT.getValue());
        if (StringUtils.isNotEmpty(userLike.getId())) {
            if (userLike.getIsLike().equals("1")) {
                userLike.setIsLike("0");
                comment.setLikeNumber(comment.getLikeNumber() - 1);
            } else {
                userLike.setIsLike("1");
                comment.setLikeNumber(comment.getLikeNumber() + 1);
            }
            baseMapper.updateById(userLike);
        } else {
            userLike.setIsLike("1");
            baseMapper.insert(userLike);
            comment.setLikeNumber(comment.getLikeNumber() + 1);
        }
        commentMapper.updateById(comment);
        //释放锁
        redisLock.unlock(lockKey);
        sendMessage(Constants.RECORD_EXCHANGE, Constants.RECORD_QUEUE_ROUTING_KEY, userLike.getUserId());
    }


    /**
     * 点赞帖子
     *
     * @param userLike
     */
    private void userLikePost(UserLike userLike) {
        //加锁
        String lockKey = "postLockKey";
        redisLock.lock(lockKey);
        Post post = postMapper.selectById(userLike.getItemId());
        userLike.setItemId(post.getId());
        userLike.setType(UserLikeTypeEnum.POST.getValue());
        if (StringUtils.isNotEmpty(userLike.getId())) {
            if (userLike.getIsLike().equals("1")) {
                userLike.setIsLike("0");
                post.setLikeNumber(post.getLikeNumber() - 1);
            } else {
                userLike.setIsLike("1");
                post.setLikeNumber(post.getLikeNumber() + 1);
            }
            baseMapper.updateById(userLike);

        } else {
            userLike.setIsLike("1");
            baseMapper.insert(userLike);
            post.setLikeNumber(post.getLikeNumber() + 1);
        }
        postMapper.updateById(post);
        //释放锁
        redisLock.unlock(lockKey);
        reLoadRedis.reloadPost(post);
        sendMessage(Constants.RECORD_EXCHANGE, Constants.RECORD_QUEUE_ROUTING_KEY, userLike.getUserId());
    }





    public void sendMessage(String exchange, String key, String userId) {
        JSONObject data = new JSONObject();
        data.put("userId", userId);
        rabbitTemplate.convertAndSend(exchange, key, data.toString());
    }


}
